package org.xielei.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wyh on 17-6-13.
 * 用来转换json
 */
public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    }

    /**
     * 获取ObjectMapper
     *
     * @return
     */
    public static ObjectMapper getMapper() {
        return mapper;
    }

    /**
     * 将obj转换为json字符串
     *
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String toJson(Object obj) {
        try {
            Assert.notNull(obj, "obj can not be null");
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串转换为对象
     *
     * @param content
     * @param cls
     * @return
     */
    public static <T extends Object> T readJson(String content, Class<T> cls) {
        try {
            return mapper.readValue(content, cls);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("转换失败");
        }
    }

    /**
     * 将字符串转换为对象
     *
     * @param map
     * @param cls
     * @return
     */
    public static <T extends Object> T readJson(Map map, Class<T> cls) {
        if (map != null) {
            return readJson(toJson(map), cls);
        }
        return null;
    }

    /**
     * 将json转为map
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static Map<String, Object> readMap(String content) {
        try {
            return mapper.readValue(content, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取JavaType
     *
     * @param collectionClass
     * @param elementClasses
     * @return
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static List readList(String json, Class cls) {
        try {
            return (List) getMapper().readValue(json, getCollectionType(ArrayList.class, cls));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
